<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline" v-if="permissionStore.hasPermisson('zbljd.cx')">
            <a-form-item :style="{ width: '280px' }" label="员工工号" label-col-flex="100px">
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                        class="bacClass" v-model="pageData.dropDownData" :filter-option="false" allow-search
                                        allow-clear @focus="focusSel('empNo')">
                                        <a-option v-for="item in pageData.nameList" :value="item['empNo']">{{
                                            item['empNo']
                                        }}</a-option>
                                    </a-select> -->
              <a-input style="width: 197px" allow-clear class="bacClass" v-model="pageData.dropDownData"
                @press-enter="huiche"></a-input>
            </a-form-item>
            <a-form-item :style="{ width: '280px' }" label="员工姓名" label-col-flex="100px">
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                        class="bacClass" v-model="pageData.dropDownData1" :filter-option="false"
                                        allow-search allow-clear @focus="focusSel('empName')">
                                        <a-option v-for="item in pageData.nameList1" :value="item['empName']">{{
                                            item['empName']
                                        }}</a-option>
                                    </a-select> -->
              <a-input style="width: 197px" allow-clear class="bacClass" v-model="pageData.dropDownData1"
                @press-enter="huiche"></a-input>
            </a-form-item>
            <CorporateSectorCascader ref="cascaderRef" :configCascader="configCascader"
              @changeCascader="changeCascader" />
            <a-form-item :style="{ width: '280px' }" label="日期">
              <!-- <a-date-picker  popup-container="html"  style="width:150px" class="bacClass" v-model="pageData.registerTime"
                                @press-enter="huiche" />至
                            <a-date-picker  popup-container="html"  style="width:150px" class="bacClass" v-model="pageData.registerTime2"
                                @press-enter="huiche" /> -->
              <a-range-picker  popup-container="html"  class="bacClass" @select="onSelect" style="width: 197px" @clear="onClear" />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar class="gesture" :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
          @export="exports" @cel="cancel">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef"
        class="ag-theme-alpine" :rowData="table.dataList" :localeText="localeText1" :columnDefs="tc"></AgGridVuesCopys>
    </template>
    <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      style="justify-content: center" />
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false" :width="400"
      unmount-on-close popup-container=".arco-tabs-content" placement="bottom" :height="pageData.rHeight"
      :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" @ok="sideOk" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="min-width: 1500px">
        <a-form ref="formRef" layout="horizontal" size="mini" :model="dataForm" :label-col-props="{ span: 8 }"
          :wrapper-col-props="{ span: 16 }">
          <a-row :gutter="16">
            <!-- tw加 -->
            <a-col :span="4">
              <a-form-item label="日期" field="donationNumber">
                <a-date-picker  popup-container="html"  v-model="riqi" :style="{ width: '200px' }" disabled />
              </a-form-item>

              <!-- --- -->
            </a-col>
            <a-col :span="4">
              <a-form-item label="异常单号" field="donationNumber" disabled>
                <a-input v-model="dataForm.donationNumber" />
              </a-form-item>
            </a-col>
            <a-col :span="8" style="display: flex">
              <CorporateSectorCascader ref="cascaderRef1" :configCascader="configCascader1"
                @changeCascader="changeCascader1" />
            </a-col>
            <a-col :span="4">
              <a-form-item label="员工姓名" field="empName" :disabled="dataForm.firmGroupsId == null">
                <a-select popup-container="html"  :class="{ bacClass: dataForm.firmGroupsId != null }" v-model="dataForm.empName"
                  @focus="getPersonnel" @change="empNameChange">
                  <a-option v-for="item in pageData.empList" :value="item.id" :key="item.id">
                    {{ item.name }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="员工工号" field="empNo" disabled>
                <a-input v-model="dataForm.empNo" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="4">
              <a-form-item label="岗位" field="postId" :disabled="dataForm.firmGroupsId == null">
                <a-select popup-container="html"  :class="{ bacClass: dataForm.firmGroupsId != null }" allow-clear v-model="dataForm.postId">
                  <a-option v-for="item in pageData.postList" :value="item.id">{{ item.post }}
                  </a-option>
                </a-select>
                <!-- <a-input :class="{'bacClass':(!pageData.isDetails)}" placeholder="请输入单位" v-model="dataForm.unit" /> -->
              </a-form-item>
            </a-col>
            <!-- <a-col :span="4">
                                <a-form-item label="日期" field="registerTime" :rules="[{ required: true, message: '日期必填' }]"
                                    :validate-trigger="['change', 'blur']">
                                    <a-date-picker  popup-container="html"  class="bacClass" v-model="dataForm.registerTime" />
                                </a-form-item>
                            </a-col> -->
            <a-col :span="4">
              <a-form-item label="班次" field="Shift">
                <a-select popup-container="html"  class="bacClass" allow-clear v-model="dataForm.Shift">
                  <a-option value="早班"> 早班 </a-option>
                  <a-option value="晚班"> 晚班 </a-option>
                </a-select>
                <!-- <a-input :class="{'bacClass':(!pageData.isDetails)}" placeholder="请输入产品类型" v-model="dataForm.materialsCategory" /> -->
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="补扣类型" field="donationType">
                <a-select popup-container="html"  class="bacClass" allow-clear v-model="dataForm.donationType" @focus="getAllBk">
                  <a-option v-for="item in pageData.bkTypeList" :value="item['typeName']">{{
                    item['typeName']
                  }}</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label-col-flex="100px" label="生产补贴类型" field="donationType">
                <a-select popup-container="html"  class="bacClass" allow-clear v-model="shengchangbutieType" @focus="selectbutie('生产补贴类型')">
                  <a-option v-for="item in shengchangbutieTypelist" :value="item['detailName']">{{
                    item['detailName']
                  }}</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label-col-flex="100px" label="生产补贴单价" field="donationType">
                <a-select popup-container="html"  class="bacClass" allow-clear v-model="shengchangbutiePrice" @focus="selectbutie('生产补贴单价')">
                  <a-option v-for="item in shengchangbutiePricelist" :value="item['detailName']">{{
                    item['detailName']
                  }}</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="4">
              <a-form-item label-col-flex="100px" label="生产补贴次数" field="donationType">
                <a-input-number v-model="shengchangbutieNum" class="input-demo bacClass" :min="0" :max="10000000000000" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="金额" field="money">
                <a-input-number v-model="dataForm.money" class="input-demo bacClass" :min="0" :max="10000000000000"
                  :precision="2" />
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="关联单号" field="relationNumberId">
                <a-input class="bacClass" v-model="dataForm.relationNumberId" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-form layout="horizontal" size="mini" :model="dataForm" :label-col-props="{ span: 1 }"
          :wrapper-col-props="{ span: 23 }">
          <a-form-item label="原因" field="reason">
            <a-textarea class="bacClass" placeholder="" style="height: 70px" v-model="dataForm.reason" auto-size
              :max-length="400" allow-clear show-word-limit />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import usePermission from '@/store/modules/permission'
import { now, template } from 'lodash'
// 引入

import { localeText } from '@/api/aggridZw'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'

interface DismantlingPayroll {
  id: any
  donationNumber: string
  registerTime: any
  registerTime2: any
  empNo: string
  empName: string
  firmGroupId: any
  firmGroupName: string
  firmGroupsId: any
  postId: any
  postName: string
  Shift: string
  donationType: string
  money: any
  relationNumberId: any
  reason: string
  remark: string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
  zuId: any
  firmName: ''
  firmTypeId: any
}
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}
const headerShow = ref<boolean>(true)

function doRefresh() {
  pageData.pageLoading = true
  post({
    url: 'pieceData/Donate/findDonate?page=' + page.value + '&limit=' + size.value,
    data: {
      deleteState: '0',
      empNo: pageData.dropDownData,
      empName: pageData.dropDownData1,
      registerTime: pageData.registerTime,
      registerTime2: pageData.registerTime2,
      firmGroupsId: pageData.firmGroupsId,
      firmName: pageData.firmName,
      firmGroupId: pageData.firmGroupId,
      firmGroupName: pageData.firmGroupName,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        table.handleSuccess(data.items)

        // 查询方法改

        gridOption.value.setRowData(data.items)

        total.value = data.page.total
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const { selectedRowKeys, onSelectionChange } = useRowSelection()
const pagination = usePagination(doRefresh)
const table = useTable()
const rowKey = useRowKey('id')
const tableColumns = useTableColumn([
  {
    title: '增补或乐捐异常单号',
    key: 'donationNumber',
    dataIndex: 'donationNumber',
    width: 150,
  },

  {
    title: '日期',
    key: 'registerTime',
    dataIndex: 'registerTime',
    width: 150,
  },
  {
    title: '员工工号',
    key: 'empNo',
    dataIndex: 'empNo',
    width: 150,
  },
  {
    title: '员工姓名',
    key: 'empName',
    dataIndex: 'empName',
    width: 150,
  },
  {
    title: '公司',
    key: 'firmName',
    dataIndex: 'firmName',
    width: 150,
  },
  {
    title: '部门',
    key: 'firmGroupName',
    dataIndex: 'firmGroupName',
    width: 150,
  },
  {
    title: '岗位',
    key: 'postName',
    dataIndex: 'postName',
    width: 150,
  },
  {
    title: '补扣类型',
    key: 'donationType',
    dataIndex: 'donationType',
    width: 200,
  },
  {
    title: '金额',
    key: 'money',
    dataIndex: 'money',
    width: 200,
  },
  {
    title: '原因',
    key: 'reason',
    dataIndex: 'reason',
    width: 200,
  },
  {
    title: '关联单号',
    key: 'relationNumberId',
    dataIndex: 'relationNumberId',
    width: 200,
  },
  {
    title: '创建人',
    key: 'createName',
    dataIndex: 'createName',
    width: 150,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    width: 200,
  },
  {
    title: '最后修改人',
    key: 'updateName',
    dataIndex: 'updateName',
    width: 150,
  },
  {
    title: '最后修改时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
    width: 200,
  },
  {
    title: '作废状态',
    key: 'toState',
    dataIndex: 'toState',
    width: 100,
    fixed: 'right',
    slotName: 'toState',
  },
  {
    title: '操作',
    key: 'id',
    slotName: 'act',
    width: 150,
    fixed: 'right',
  },
])

let tc: any[] = tableColumns.map((o) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
    tooltipField: o.key,
  }
  if (o.slotName === 'act') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'right'
    obj['width'] = 100
    obj['cellRenderer'] = {
      template: `<a-tag color="#ff7d00" class="gesture" @click="a" v-if="e">修改</a-tag>`,
      setup(props: any) {
        const a = () => {
          editHandler(props.params.data)
        }
        return {
          a,
          e: props.params.data.toState == 0,
        }
      },
    }
  }
  if (o.slotName === 'toState') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'right'
    obj['width'] = 100
    obj['cellRenderer'] = {
      template: `<a-tag color="#f53f3f" v-if="params.data.toState==1">{{val}}</a-tag><a-tag color="green" v-else>{{val}}</a-tag>`,
      setup(props: any) {
        let val = ref()
        if (props.params.data.toState == 0) {
          val.value = '未作废'
        } else {
          val.value = '已作废'
        }

        return {
          val,
        }
      },
    }
  }

  return obj
})

let a = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
]
tc = a.concat(tc)

const tableColumns1 = useTableColumn([
  {
    title: '拆纱单号',
    key: 'brandCode',
    dataIndex: 'brandCode',
    width: 150,
  },

  {
    title: '拆纱重量',
    key: 'brandName',
    dataIndex: 'brandName',
    width: 150,
  },
  {
    title: '拆纱日期',
    key: 'clothClass',
    dataIndex: 'clothClass',
    width: 150,
  },
  {
    title: '单价',
    key: 'remark',
    dataIndex: 'remark',
    width: 150,
  },
  {
    title: '单位',
    key: 'remark',
    dataIndex: 'remark',
    width: 150,
  },
  {
    title: '金额',
    key: 'remark',
    dataIndex: 'remark',
    width: 150,
  },
  {
    title: '员工',
    key: 'createName',
    dataIndex: 'createName',
    width: 150,
  },
])

let tc1: any[] = tableColumns1.map((o) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
    tooltipField: o.key,
  }
  if (o.slotName === 'act') {
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj['lockPosition'] = 'right'

    obj['cellRenderer'] = {
      template: `<a-tag color="#ff7d00" v-if="isEdit" class="gesture" v-if="e" @click="a">修改</a-tag>`,
      setup(props: any) {
        const a = () => {
          editHandler(props.params.data)
        }
        let isEdit = permissionStore.hasPermisson('zbljd.xg')
        return {
          e: pageData.isEdit,
          a,
          isEdit,
        }
      },
    }
  }

  return obj
})

tc1 = a.concat(tc1)
const pageData = reactive<{
  showAdd: boolean
  sideTitle: string
  dropDownData: any
  nameList: []
  pageLoading: boolean
  typeList: []
  dropDownData1: any
  rHeight: any
  btnList: any[]
  isEdit: boolean
  dismantlingSheetNumber: any[]
  dismantlingSheetNumberList: any[]
  addDataList: any[]
  firmList: any[]
  bmList: any[]
  postList: any[]
  empList: any[]
  zuList: any[]
  bkTypeList: any[]
  registerTime: any
  registerTime2: any
  dropDownData2: any
  nameList1: any[]
  nameList2: any[]
  firmGroupsId: any
  firmName: any
  firmGroupId: any
  firmGroupName: any
}>({
  nameList: [],
  showAdd: false,
  sideTitle: '新增增补乐捐异常单',
  dropDownData: '',
  pageLoading: false,
  typeList: [],
  dropDownData1: '',
  rHeight: 0,
  btnList: [],
  isEdit: false,
  dismantlingSheetNumber: [],
  dismantlingSheetNumberList: [],
  addDataList: [],
  firmList: [],
  bmList: [],
  postList: [],
  empList: [],
  zuList: [],
  bkTypeList: [],
  registerTime: '',
  registerTime2: '',
  dropDownData2: '',
  nameList1: [],
  nameList2: [],
  firmGroupsId: '',
  firmName: '',
  firmGroupId: '',
  firmGroupName: '',
})
let field = ''
//下拉框得到焦点
const focusSel = (val: any) => {
  field = val
  let ob = {}
  ob[field] = ''
  selCxAll(ob)
}
//下拉数据
const options = ref<any>(pageData.nameList)
const loading = ref(false)
const handleSearch = (value: any) => {
  if (value) {
    const ob = { field: value }
    loading.value = true
    selCxAll(ob)
    if (field == 'empNo') {
      options.value = pageData.nameList
    } else if (field == 'empName') {
      options.value = pageData.nameList1
    } else if (field == 'firmGroupName') {
      options.value = pageData.nameList2
    }

    loading.value = false
  } else {
    options.value = []
  }
}

//下拉框查询
function selCxAll(val: any) {
  post({
    url: 'pieceData/Donate/findDonate2',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      if (field == 'empNo') {
        pageData.nameList = data.items
      } else if (field == 'empName') {
        pageData.nameList1 = data.items
      } else if (field == 'firmGroupName') {
        pageData.nameList2 = data.items
      }
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}
let cascaderRef = ref('')
let configCascader = ref<{}>({
  corporateWidth: '180px', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: false, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '公司', //公司label
  sectorName: '部门', //部门label
})
let configCascader1 = ref<{}>({
  corporateWidth: '155px', //公司宽度
  sectorWidth: '155px', //部门宽度
  corporateRquired: true, //公司是否必填
  sectorRquired: true, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '公司', //公司label
  sectorName: '组别', //部门label
})
interface obj {
  sectorId: ''
  corporateId: ''
  corporateLabel: ''
  sectorLabel: ''
}
const changeCascader1 = (data: obj) => {
  const { corporateId, sectorId, sectorLabel, corporateLabel } = data
  dataForm.firmGroupsId = corporateId
  dataForm.firmName = corporateLabel
  dataForm.firmGroupId = sectorId
  dataForm.firmGroupName = sectorLabel
}
const changeCascader = (data: obj) => {
  const { corporateId, sectorId, sectorLabel, corporateLabel } = data
  pageData.firmGroupsId = corporateId
  pageData.firmName = corporateLabel
  pageData.firmGroupId = sectorId
  pageData.firmGroupName = sectorLabel
}
onMounted(() => {
  riqi.value = getnowdate()
  // 切换tap到本页面执行的方法
  emitter.on('BrandInfo', () => {
    // selCxAll1({});
    doRefresh()
  })
  pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight - 100
  }
  window.addEventListener('resize', () => {
    pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
      pageData.rHeight = pageData.rHeight - 100
    }
  })
})
let cxbl = ''
//查询
const selectHandler = () => {
  pagination.page = 1
  cxbl = pageData.dropDownData
  doRefresh()
}
const queryData = reactive({
  clothType: '',
})
const addHandler = () => {
  for (var key in dataForm) {
    if (
      key === 'id' ||
      key === 'firmGroupId' ||
      key === 'firmGroupsId' ||
      key === 'postId' ||
      key === 'postId'
    ) {
      dataForm[key] = null
    } else if (key === 'money') {
      dataForm[key] = 0
    } else {
      dataForm[key] = ''
    }
  }
  pageData.showAdd = true
  pageData.sideTitle = '新增增补乐捐异常单'
  getPostList()
}
const dataForm = reactive<DismantlingPayroll>({
  id: null,
  donationNumber: '',
  registerTime: null,
  registerTime2: null,
  empNo: '',
  empName: '',
  firmGroupId: null,
  firmGroupName: '',
  firmGroupsId: null,
  postId: null,
  postName: '',
  Shift: '',
  donationType: '',
  money: null,
  relationNumberId: null,
  reason: '',
  remark: '',
  createName: '',
  createTime: '',
  updateName: '',
  updateTime: '',
  zuId: null,
  firmName: '',
  firmTypeId: null,
})

// 表格准备事件
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}

let formRef = ref<FormInstance>()
const sideOk = () => {
  if (dataForm.firmGroupsId ? false : true) {
    Message.error('请选择公司')
    return
  }
  formRef.value?.validate().then((err) => {
    if (!err) {
      let list = pageData.postList.filter(function (o: any) {
        return dataForm['postId'] == o['id']
      })

      if (list.length != 0) {
        dataForm.postName = list[0]['post']
      }
      pageData.pageLoading = true
      dataForm['produceSubsidyType'] = shengchangbutieType.value
      dataForm['produceSubsidyPrice'] = Number(shengchangbutiePrice.value)
      dataForm['produceSubsidyNumber'] = Number(shengchangbutieNum.value)
      if (pageData.sideTitle === '新增增补乐捐异常单') {
        post({
          url: 'pieceData/Donate/insert',
          data: [dataForm],
        })
          .then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              pageData.showAdd = false

              Message.success({
                content: '新增成功',
                duration: 5000,
              })
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              })
            }
            doRefresh()
          })
          .finally(() => {
            doRefresh()
            pageData.pageLoading = false
          })
      } else {
        post({
          url: 'pieceData/Donate/updateDonate',
          data: [dataForm],
        })
          .then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              pageData.showAdd = false
              Message.success({
                content: '修改成功',
                duration: 5000,
              })
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              })
            }
          })
          .finally(() => {
            doRefresh()
            pageData.pageLoading = false
          })
      }
    }
  })
}
const deleteHandler = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  let list = gridOption.value.getSelectedRows()
  list.forEach(function (o: any) {
    o['deleteState'] = 1
  })
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      pageData.pageLoading = true
      post({
        url: 'pieceData/Donate/updateDonate',
        data: list,
      })
        .then(({ code, data }: any) => {
          if (code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000,
            })
            pagination.page = 1
            doRefresh()
          } else {
            Message.error({
              content: '删除失败',
              duration: 5000,
            })
          }
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    },
  })
}

let curobj = null
const editHandler = (record: DismantlingPayroll) => {
  curobj = record

  shengchangbutieType.value = record['produceSubsidyType']
  shengchangbutiePrice.value = record['produceSubsidyPrice']
  shengchangbutieNum.value = record['produceSubsidyNumber']

  for (var key in record) {
    dataForm[key] = record[key]
  }
  pageData.sideTitle = '修改增补乐捐异常单'
  pageData.showAdd = true
  getPostList()
  getFrimList({ firmName: '', department: '' }, 1)
  getFrimList({ firmName: record.firmName, department: '', firmTypeId: record.firmTypeId }, 2)
  getFrimList(
    {
      firmName: record.firmName,
      department: record.firmGroupName,
      firmTypeId: record.firmTypeId,
    },
    3
  )
}
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
  return new Promise<void>((resolve) => {
    if (window.encodeURI(value).indexOf('%') !== -1) {
      cb('填写的值不能包含中文！')
    }
    resolve()
  })
}

//导出
const exports = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  } else {
    let idList: any = []
    gridOption.value.getSelectedRows().forEach(function (o: any) {
      idList.push(o['id'])
    })
    //将表头拼接出来
    let head =
      '<th>增补或乐捐异常单号</th><th>日期</th><th>员工工号</th><th>员工姓名</th><th>部门</th><th>岗位</th><th>补扣类型</th><th>金额</th><th>原因</th><th>关联单号</th><th>作废状态</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
    //拿到当前表格数据与勾选的行做筛选

    let nowRow = table.dataList.filter(function (o) {
      return (
        gridOption.value
          .getSelectedRows()
          .map((o: any) => {
            return o.id
          })
          .indexOf(o['id']) !== -1
      )
    })
    let body = ''
    nowRow.forEach(function (o) {
      body += '<tr><td>' + o['donationNumber'] + '</td>'
      body += '<td>' + o['registerTime'] + '</td>'
      body += '<td>' + o['empNo'] + '</td>'
      body += '<td>' + o['empName'] + '</td>'
      body += '<td>' + o['firmGroupName'] + '</td>'
      body += '<td>' + o['postName'] + '</td>'
      body += '<td>' + o['donationType'] + '</td>'
      body += '<td>' + o['money'] + '</td>'
      body += '<td>' + o['reason'] + '</td>'
      body += '<td>' + o['relationNumberId'] + '</td>'
      body += '<td>' + (o['toState'] == 0 ? '未作废' : '已作废') + '</td>'
      body += '<td>' + o['createName'] + '</td>'
      body += '<td>' + o['createTime'] + '</td>'
      body += '<td>' + o['updateName'] + '</td>'
      body += '<td>' + o['updateTime'] + '</td>'
      body += '</tr>'
    })
    tableToXlsx(head, '增补乐捐异常单', body)
    console.log(table)
  }
}

function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  document.removeChild(a)
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}

const localeText1: any = ref(localeText)
//作废
const cancel = () => {
  if (gridOption.value.getSelectedRows().length == 0) {
    Message.warning({
      content: '请勾选一条数据',
      duration: 5000,
    })
    return
  }
  let rowData = gridOption.value.getSelectedRows()
  rowData.forEach(function (o: any) {
    o['toState'] = 1
  })
  post({
    url: 'pieceData/Donate/updateDonate',
    data: rowData,
  })
    .then((res: any) => {
      if (res.code === 200) {
        formRef.value?.resetFields()
        pageData.showAdd = false

        Message.success({
          content: '修改成功',
          duration: 5000,
        })
      } else {
        Message.error({
          content: res.message,
          duration: 5000,
        })
      }
      doRefresh()
    })
    .finally(() => {
      pageData.pageLoading = false
    })
}
//拿到所有公司
const foucusUseFrim = (num: any) => {
  let ob = {
    firmGroupsId: '',
    firmGroupId: '',
    firmGroupName: '',
    firmName: '',
  }
  if (num == 1) {
    ob['firmName'] = ''
    ob['department'] = ''
    // ob['firmTypeId'] = ""
  }
  if (num == 2) {
    if (dataForm.firmGroupsId !== '' && dataForm.firmGroupsId !== undefined) {
      let list = pageData.firmList.filter(function (o: any) {
        return o['id'] == dataForm.firmGroupsId
      })
      ob['firmName'] = list[0]['firmName']
      dataForm.firmName = list[0]['firmName']
      dataForm.firmTypeId = list[0]['firmTypeId']
      ob['department'] = list[0]['department']
      ob['firmTypeId'] = list[0]['firmTypeId']
    } else {
      Message.warning({
        content: '请先选择公司',
        duration: 5000,
      })
    }
  }
  getFrimList(ob, num)
}
const options2 = ref(pageData.firmList)
const loading2 = ref(false)

function getFrimList(ob: any, nums: any) {
  // post({
  //   url: 'org/firmGroup/getFirmInfoByMap',
  //   data: ob,
  // }).then((result: any) => {
  //   if (result.code === 200) {
  //     if (nums == 1) {
  //       pageData.firmList = result.data
  //     }
  //     if (nums == 2) {
  //       pageData.bmList = result.data
  //     }
  //     if (nums == 3) {
  //       pageData.zuList = result.data
  //     }
  //   } else {
  //     Message.error(result.message)
  //   }
  // })
}
//查询岗位
function getPostList() {
  post({
    url: 'org/baPost/getList',
    data: {
      company_id: dataForm.firmGroupsId,
    },
  }).then((result: any) => {
    if (result.code === 200) {
      pageData.postList = result.data
    } else {
      Message.error(result.message)
    }
  })
}
// 指派人员接口
function getPersonnel() {
  //查所有的员工
  post({
    url: 'org/hrEmployee/getList',
    data: {
      company_id: dataForm.firmGroupsId,
      deleteState: 0,
      department_id: dataForm.firmGroupId,
      obsoleteState: 0,
    },
  }).then((res) => {
    if (res.code == 200) {
      pageData.empList = res.data
    } else {
      Message.error({
        content: res['message'],
        duration: 5000,
      })
    }
  })
}
//查询所有补扣类型
function getAllBk() {
  post({
    url: 'pieceData/fillDeductType/getList',
    data: {
      deleteState: 0,
    },
  }).then((res) => {
    if (res.code == 200) {
      pageData.bkTypeList = res.data
    } else {
      Message.error({
        content: res['message'],
        duration: 5000,
      })
    }
  })
}
//员工工号改变查出员工姓名
function empNoChange(empNo: any) {
  let list = pageData.empList.filter(function (o: any) {
    return o['empNo'] == empNo
  })
  if (list.length != 0) {
    dataForm['empName'] = list[0]['empName']
  }
}
//员工姓名改变查出员工工号
function empNameChange(event: any) {
  console.log(event)
  let empList = pageData.empList.filter((item) => {
    return item.id == event
  })
  dataForm.empNo = empList[0].code
  //   let list = pageData.empList.filter(function (o: any) {
  //     return o['empName'] == empName
  //   })
  //   if (list.length != 0) {
  //     dataForm['empNo'] = list[0]['empNo']
  //   }
}
const huiche = () => {
  doRefresh()
}
const onSelect = (dateString: any) => {
  pageData.registerTime = dateString[0]
  pageData.registerTime2 = dateString[1]
}
const onClear = () => {
  pageData.registerTime = ''
  pageData.registerTime2 = ''
}
//日期
const riqi = ref('') as any
//生产补贴类型
const shengchangbutieType = ref('') as any
const shengchangbutieTypelist = ref([]) as any
//生产补贴单价
const shengchangbutiePrice = ref('') as any
const shengchangbutiePricelist = ref([]) as any
//生产补贴次数
const shengchangbutieNum = ref(0)
const getnowdate = () => {
  var a = new Date().getTime()
  var b = new Date(a)
  var year = b.getFullYear() //年份
  var month = (b.getMonth() + 1) as any //月份（0-11）
  var tian = b.getDate() as any //天数（1到31）
  var hour = b.getHours() //小时数（0到23）
  var minute = b.getMinutes() //分钟数（0到59）
  var second = b.getSeconds() //秒数（0到59）

  month = month < 10 ? '0' + month : month
  tian = tian < 10 ? '0' + tian : tian
  return year + '-' + month + '-' + tian + ' ' + hour + ':' + minute + ':' + second
}
const selectbutie = (val: any) => {
  if (val == '生产补贴类型') {
    post({
      url: 'dict/dictTypeDetail/getListByCodeType?codeType=24',
    }).then((res) => {
      if (res.code == 200) {
        sessionStorage.setItem('生产补贴类型', JSON.stringify(res))
        shengchangbutieTypelist.value = res.data
      } else {
        Message.error({
          content: res['message'],
          duration: 5000,
        })
      }
    })
  } else if (val == '生产补贴单价') {
    post({
      url: 'dict/dictTypeDetail/getListByCodeType?codeType=25',
    }).then((res) => {
      if (res.code == 200) {
        shengchangbutiePricelist.value = res.data
      } else {
        Message.error({
          content: res['message'],
          duration: 5000,
        })
      }
    })
  }
}
// :items="['查询', '新增', '删除', '导出', '作废']"
const permissionStore = usePermission()
if (permissionStore.hasPermisson('zbljd.cx')) {
  pageData.btnList.push('查询')
}
if (permissionStore.hasPermisson('zbljd.xz')) {
  pageData.btnList.push('新增')
}
if (permissionStore.hasPermisson('zbljd.sc')) {
  pageData.btnList.push('删除')
}
if (permissionStore.hasPermisson('zbljd.dc')) {
  pageData.btnList.push('导出')
}
if (permissionStore.hasPermisson('zbljd.zf')) {
  pageData.btnList.push('作废')
}

</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>